<template>
	<view class="login-container">
		<uv-toast ref="loginToast"></uv-toast>
		<!-- 顶部Logo区域 -->
		<view class="content">
			<view class="header">
				<image class="logo" src="/static/lyf.jpg" mode="aspectFit"></image>
				<text class="main-title">欢迎使用原野童年</text>
				<text class="sub-title">观看课程 获取早餐券</text>
			</view>

			<!-- 身份选择区域 -->
			<view class="identity-section">
				<text class="section-title">选择您的身份开始使用</text>
				<view class="identity-options">
					<view class="identity-item" :class="{ active: selectedIdentity === 'user', disabled: hasUserToken }"
						@tap="!hasUserToken && selectIdentity('user')">
						<uv-icon name="account" size="32" :color="getIdentityColor('user')"
							:bold="selectedIdentity === 'user'">
						</uv-icon>
						<text class="identity-text"
							:style="{ color: getIdentityColor('user'), fontWeight: selectedIdentity === 'user' ? 'bold' : 'normal' }">我是用户</text>
						<text class="identity-desc">{{ hasUserToken ? '已登录' : '观看课程 领取早餐' }}</text>
					</view>

					<view class="identity-item"
						:class="{ active: selectedIdentity === 'merchant', disabled: hasShopToken }"
						@tap="!hasShopToken && selectIdentity('merchant')">
						<uv-icon name="shop_fill" size="32" custom-prefix="custom-icon"
							:color="getIdentityColor('merchant')" :bold="selectedIdentity === 'merchant'">
						</uv-icon>
						<text class="identity-text"
							:style="{ color: getIdentityColor('merchant'), fontWeight: selectedIdentity === 'merchant' ? 'bold' : 'normal' }">我是商家</text>
						<text class="identity-desc">{{ hasShopToken ? '已登录' : '管理店铺 核销验券' }}</text>
					</view>
				</view>
			</view>

			<!-- 登录表单区域 -->
			<view class="login-section" v-if="selectedIdentity">
				<!-- 用户登录 -->
				<button v-if="selectedIdentity === 'user'" class="wx-login-btn" open-type="getPhoneNumber"
					@getphonenumber="handleGetPhoneNumber">
					<!-- <uv-icon name="weixin-fill" color="#fff" size="32"></uv-icon> -->
					<text>手机号快捷登录</text>
				</button>

				<!-- 商家登录 -->
				<view v-else class="merchant-login-form">
					<view class="input-group">
						<uv-input v-model="loginForm.account" placeholder="请输入手机号" :border="true" prefixIcon="phone"
							maxlength="11" @input="validatePhone" @focus="handleInputFocus('account')"
							@blur="handleInputBlur('account')" :customStyle="getInputStyle('account')">
							<template #prefix>
								<uv-icon name="phone" size="28" :color="focusedInput === 'account' ? '#3c9cff' : '#666'"
									custom-class="input-icon"></uv-icon>
							</template>
						</uv-input>
						<text class="error-tip" v-if="phoneError">{{ phoneError }}</text>
					</view>
					<view class="input-group">
						<uv-input v-model="loginForm.password" :type="showPassword ? 'text' : 'password'"
							placeholder="请输入密码" :border="true" prefixIcon="lock" @focus="handleInputFocus('password')"
							@blur="handleInputBlur('password')" :customStyle="getInputStyle('password')">
							<template #prefix>
								<uv-icon name="lock" size="28" :color="focusedInput === 'password' ? '#3c9cff' : '#666'"
									custom-class="input-icon"></uv-icon>
							</template>
							<template #suffix>
								<uv-icon :name="showPassword ? 'eye-fill' : 'eye-off'" size="28"
									:color="focusedInput === 'password' ? '#3c9cff' : '#999'"
									@click="togglePasswordVisibility" custom-class="input-icon"></uv-icon>
							</template>
						</uv-input>
					</view>
					<button class="merchant-login-btn" @tap="handleMerchantLogin">登录</button>
					<view class="form-footer">
						<text class="forget-pwd" @tap="handleForgetPassword">忘记密码？</text>
					</view>
				</view>
			</view>

			<!-- 商家入驻按钮 -->
			<view class="merchant-register" v-if="selectedIdentity === 'merchant'">
				<text class="register-text">还没有店铺账号？</text>
				<text class="register-btn" @tap="handleMerchantRegister">立即入驻</text>
			</view>

			<!-- 用户协议部分 -->
			<view class="agreement-section" :class="{ 'shake': showAgreementError }" @animationend="handleAnimationEnd">
				<view class="checkbox" @tap="toggleAgreement">
					<uv-icon v-if="isAgreed" color="#3c9cff" size="32" name="checkmark-circle-fill"></uv-icon>
					<view class="box" v-else
						style="width: 24rpx; height: 24rpx; border: 1px solid #3c9cff;border-radius: 50%;">
					</view>
				</view>
				<text class="agreement-text">
					登录即表示同意<text class="link" @tap.stop="openAgreement('user')">用户协议</text>和<text class="link"
						@tap.stop="openAgreement('privacy')">隐私政策</text>
				</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				selectedIdentity: '',
				loginForm: {
					account: '',
					password: ''
				},
				showPassword: false,
				phoneError: '',
				focusedInput: '',
				isAgreed: false,
				showAgreementError: false,
				hasUserToken: false,
				hasShopToken: false,
				registerMerchantId: 0
			}
		},
		onLoad(options) {
			if (options.q) {
				let url = decodeURIComponent(options.q);
				url = url.substring(url.lastIndexOf('=') + 1);
				uni.setStorageSync('register_merchant_id', url);
			}
			const merchantId = uni.getStorageSync('register_merchant_id');
			if (merchantId) {
				this.registerMerchantId = merchantId;
			}
			// 检查token状态
			this.checkTokenStatus();

			// 获取路径参数中的mode
			const mode = options.mode || '0';

			// 根据mode和token状态设置选中的身份
			if (mode === '1' && !this.hasShopToken) {
				this.selectedIdentity = 'merchant';
			} else if (mode === '0' && !this.hasUserToken) {
				this.selectedIdentity = 'user';
			}

			// 重置表单
			this.loginForm = {
				account: '',
				password: ''
			};
			this.phoneError = '';
		},
		methods: {
			// 显示提示信息
			showToast(msg, type, duration) {
				this.$refs.loginToast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			checkTokenStatus() {
				// 检查用户token
				const userToken = uni.getStorageSync('token');
				this.hasUserToken = !!userToken;

				// 检查商家token
				const shopToken = uni.getStorageSync('shop_token');
				this.hasShopToken = !!shopToken;
			},
			selectIdentity(identity) {
				// 检查是否已登录
				if ((identity === 'user' && this.hasUserToken) ||
					(identity === 'merchant' && this.hasShopToken)) {
					return;
				}

				if (identity !== 'user' && identity !== 'merchant') {
					return;
				}

				this.selectedIdentity = identity;
				// 切换身份时重置表单
				this.loginForm = {
					account: '',
					password: ''
				};
				this.phoneError = '';
			},
			validatePhone(value) {
				const phoneReg = /^1[3-9]\d{9}$/;
				if (value && !phoneReg.test(value)) {
					this.phoneError = '请输入正确的手机号';
				} else {
					this.phoneError = '';
				}
			},
			togglePasswordVisibility() {
				this.showPassword = !this.showPassword;
			},
			handleMerchantRegister() {
				uni.navigateTo({
					url: '/subpkg/register_merchant/register_merchant'
				});
			},
			async handleGetPhoneNumber(e) {
				console.log(e)
				if (!this.isAgreed) {
					this.showAgreementError = true;
					return;
				}

				try {
					// 检查是否成功获取手机号码加密数据
					if (!e.detail.code) {
						throw new Error('未获得手机号码授权');
					}

					uni.showLoading({
						title: '登录中...'
					});

					const result = e.detail;

					// 发送数据获取获取手机号码继续登录
					const data = await this.fetchUserPhone(result.code);

					// 获取登录code
					const {
						code
					} = await uni.login({
						provider: 'weixin'
					});

					if (!code) {
						throw new Error('获取不到用户标识');
					}

					const token = await this.$http.post(
						`/auth/mini/login?phone=${data}&code=${code}&shopId=${this.registerMerchantId}`);
					// 查看是否获取到token
					if (token) {
						uni.setStorageSync('token', token);
						uni.removeStorageSync('register_merchant_id');
					}

					uni.reLaunch({
						url: `/pages/my/index?mode=0`
					});
				} catch (error) {
					this.showToast(error.msg, 'default', 1000);
				} finally {
					uni.hideLoading();
				}
			},
			async fetchUserPhone(code) {
				try {
					// 发送请求获取用户手机号
					const phone = await this.$http.get(`/auth/wechat/phone?code=${code}`);
					if (phone) {
						return phone;
					} else {
						throw new Error('获取手机号失败');
					}
				} catch (error) {
					console.error(error);
					throw new Error('获取手机号失败');
				}
			},
			async handleMerchantLogin() {
				// 验证表单
				if (!this.loginForm.account.trim() || !this.loginForm.password.trim()) {
					uni.showToast({
						title: '账号和密码不能为空',
						icon: 'none'
					});
					return;
				}

				// 验证协议
				if (!this.isAgreed) {
					this.showAgreementError = true;
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '登录中'
					});

					const data = await this.$http.post('/auth/merchant/login', {
						account: this.loginForm.account.trim(),
						password: this.loginForm.password.trim()
					});

					if (data) {
						// 存储商家token
						uni.setStorageSync('shop_token', data);
						// 登录成功后跳转
						uni.reLaunch({
							url: '/pages/my/index?mode=1'
						});
					}
				} catch (error) {
					this.showToast(error.msg, 'default', 1000);
				} finally {
					uni.hideLoading();
				}
			},
			handleForgetPassword() {
				// 忘记密码逻辑
			},
			handleInputFocus(inputName) {
				this.focusedInput = inputName;
			},
			handleInputBlur(inputName) {
				this.focusedInput = '';
			},
			getInputStyle(inputName) {
				return {
					borderColor: this.focusedInput === inputName ? '#3c9cff' : '#dcdfe6',
					transition: 'all 0.3s'
				}
			},
			toggleAgreement() {
				this.isAgreed = !this.isAgreed;
			},
			handleAnimationEnd() {
				this.showAgreementError = false;
			},
			openAgreement(type) {
				// 跳转到协议页面
				uni.navigateTo({
					url: `/subpkg/agreement/agreement?type=${type}`
				});
			},
			getIdentityColor(identity) {
				if ((identity === 'user' && this.hasUserToken) ||
					(identity === 'merchant' && this.hasShopToken)) {
					return '#999'; // 禁用状态的颜色
				}
				return this.selectedIdentity === identity ? '#3c9cff' : '#666';
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'login_page.scss';

	.identity-item {
		// ... 现有样式 ...

		&.disabled {
			opacity: 0.6;
			cursor: not-allowed;

			.identity-text {
				color: #999 !important;
			}

			.identity-desc {
				color: #999;
			}
		}
	}
</style>